package com.zhongfl.crm.service.impl.boss;

import com.zhongfl.crm.enums.boss.SequenceTypeEnum;
import com.zhongfl.crm.lixiao.mapper.SequenceMapper;
import com.zhongfl.crm.service.boss.SequenceAtomService;
import com.zhongfl.crm.model.boss.Sequence;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 序列号生产器
 * 用户系统中编号需要保证唯一，并且呈递增序列的单号
 *
 * @author wang.yuchuan
 * @date 2018/9/30
 */
@Service
@Slf4j
public class SequenceAtomServiceImpl implements SequenceAtomService {

    @Resource
    private SequenceMapper sequenceMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer getNextId(SequenceTypeEnum sequenceTypeEnum) {
        Sequence sequence = new Sequence(sequenceTypeEnum.toString(), -1);
        Sequence result = sequenceMapper.getSequence(sequence);
        if (result == null) {
            log.warn("A null sequence was returned from the database {}", sequence);
            Sequence entity = new Sequence(sequenceTypeEnum.toString(), 0);
            sequenceMapper.insert(entity);
            //重新调用一次
            result = sequenceMapper.getSequence(sequence);
        }
        Sequence parameterObject = new Sequence(sequenceTypeEnum.toString(), result.getNextId() + 1);
        sequenceMapper.updateSequence(parameterObject);
        return result.getNextId();
    }
}
